/*
 *  SableJBDD, a Java Binary Decision Diagram package.
 *  Copyright (C) 2003  Feng Qian
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2.1 of the License, or (at your option) any later version.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
//$Id: WeakUniqueTable.java,v 1.4 2004/03/12 00:16:09 fqian Exp $

package SableJBDD.bdd.internal;

import java.io.PrintStream;
import java.lang.ref.WeakReference;

import SableJBDD.bdd.JBddNode;
import SableJBDD.bdd.JBddVariable;

/**
 * A weak unique table is a unique table using weak references to objects.
 * It does not prevents referred objects from being garbage collected.
 *
 * @author Feng Qian
 */
public class WeakUniqueTable extends AbstractUniqueTable {
  // JBddInternalNode pool
  private final BddNodeFactory nodeFactory;         // node pooling
  private final static int DEFAULT_BDDNODE_POOL_SIZE = 1000000; // 5 M
  /** 
   * Defines  a unique table with a specific number of entries. 
   */
  public WeakUniqueTable(int size) {
    this(size, new NonReclaimableNodePool(DEFAULT_BDDNODE_POOL_SIZE));
  }               
 
  public WeakUniqueTable(int size, BddNodeFactory factory) {
    super(size);
    this.nodeFactory = factory;
  }
  
  // implement abstract from super class
  protected Element newElement(JBddNode node, Element next) {
    return new WeakElement(node, next);
  }
 
  protected JBddNode makeNode(JBddVariable var, JBddNode low, JBddNode high) {
    return this.nodeFactory.getFreshNode(var, low, high);
  }
  
  public void reportStatistics(PrintStream out) {
    super.reportStatistics(out);
    this.nodeFactory.reportStatistics(out);
  }
  
  // an element is a weak reference to a BddNode, and has the link to 
  // the next element.
  class WeakElement extends WeakReference implements Element{
    private Element next;
    
    WeakElement(JBddNode node, Element next) {
      super(node);
      this.next = next;
    }
        
    // check if the soft reference is GCed.
    public boolean isEmpty() {
      return (get() == null);
    }
    
    // get node of this element, it might be null
    public JBddNode getNode() {
      return (JBddNode)get();
    }

    public Element getNext() {
      return this.next;
    }

    public void setNext(Element el) {
      this.next = el;
    }
  }
}


